import os,sys
from optparse import OptionParser,make_option
from time import sleep
from syslog import *
from pyinotify import *




class RsyncEvent(ProcessEvent):
  pretend = None

  def __init__(self, pretend=False):
    self.pretend = pretend

  def sync(self, wpath):
    args = [config.rsync, "-ltrp", "--delete"]
    if config.extra:
      args.append(config.extra)
    args.append("--bwlimit=%s" % config.rspeed)
    if config.logfile:
      args.append("--log-file=%s" % config.logfile)
    if "rexcludes" in dir(config):
      for rexclude in config.rexcludes:
        args.append("--exclude=%s" % rexclude)
    args.append(wpath)
    rpath = config.rpaths[config.wpaths.index(wpath)]
    args.append("%s")
    cmd = " ".join(args)
    for node in config.rnodes:
      if self.pretend:
        syslog("would execute `%s'" % (cmd % (node + rpath)))
      else:
        syslog(LOG_DEBUG, "executing %s" % (cmd % (node + rpath)))
        proc = os.popen(cmd % (node + rpath))
        for line in proc:
          syslog(LOG_DEBUG, "[rsync] %s" % line.strip())

  def process_default(self, event):
    syslog(LOG_DEBUG, "caught %s on %s" % \
        (event.maskname, os.path.join(event.path, event.name)))
    for wpath in config.wpaths:
      if os.path.realpath(wpath) in os.path.realpath(event.path):
        self.sync(wpath)
        break